package com.kkd.kkdapp.view.rainView;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.utils.SystemUtils;

public class RainView extends BaseView {

	private ArrayList<RainItem> list = new ArrayList<RainItem>();
	private int rainNum = 80;
	private int size;
	private int rainColor;
	private boolean randColor;
	private int[] colors = { R.drawable.icon_happy_01, R.drawable.icon_happy_02 };
	private Handler mHandler = new Handler();
	private View secondVeiw;
	private MediaPlayer mediaPlayer;

	public RainView(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray ta = context.obtainStyledAttributes(attrs,
				R.styleable.RainView);
		rainNum = ta.getInteger(R.styleable.RainView_rainNum, 80);
		size = ta.getInteger(R.styleable.RainView_size, 20);
		rainColor = ta.getInteger(R.styleable.RainView_rainColor, 0xffffff);
		randColor = ta.getBoolean(R.styleable.RainView_randColor, false);
		ta.recycle();
		mediaPlayer = MediaPlayer.create(getContext(), R.raw.liu);
		try {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.reset();
			}
			mediaPlayer.setLooping(false);
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {

		}
	}

	public RainView(Context context) {
		super(context);
	}

	@Override
	protected void drawSub(Canvas canvas) {
		for (int i = 0; i < list.size(); i++) {
			list.get(i).draw(canvas);
		}
	}

	public void setView(View view) {
		secondVeiw = view;
	}

	@Override
	protected void logic() {
		for (int i = 0; i < list.size(); i++) {
			list.get(i).move();
		}
		int num_canSee = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).startY > list.get(i).height) {
				num_canSee++;
			}
		}
		if (num_canSee == list.size()) {
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					if (secondVeiw != null
							&& (secondVeiw.getVisibility() != View.VISIBLE)) {
						setVisibility(View.GONE);
						try {
							mediaPlayer.stop();
							mediaPlayer.release();
						} catch (Exception e) {

						}
						secondVeiw.setVisibility(View.VISIBLE);
						if (mStopAnimation != null) {
							mStopAnimation.stop(true);
						}
					}
				}
			});
		}
	}

	@Override
	protected void init() {
		for (int i = 0; i < rainNum; i++) {
			int y = -SystemUtils.dip2px(getContext(), 20 * i);
			RainItem item = new RainItem(getWidth(), getHeight(), size,
					colors[i % 2], getContext(), y);
			list.add(item);
		}
	}

	private StopAnimation mStopAnimation;

	public void setStopAnimation(StopAnimation mStopAnimation) {
		this.mStopAnimation = mStopAnimation;
	}

	public interface StopAnimation {
		public void stop(boolean stopFlg);
	}
}
